package com.scs.application.modules.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.entity.Location;
import com.scs.application.modules.base.entity.LocationLimitMatr;
import com.scs.application.modules.base.entity.MatrUnit;
import com.scs.application.modules.base.entity.Warehouse;
import com.scs.application.modules.base.mapper.LocationLimitMatrMapper;
import com.scs.application.modules.base.service.LocationLimitMatrService;
import com.scs.application.modules.base.service.LocationService;
import com.scs.application.modules.base.service.MatrUnitService;
import com.scs.application.modules.base.service.WarehouseService;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.wm.entity.Stock;
import com.scs.application.modules.wm.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 库位耗材范围 服务实现类
 * </p>
 */
@Service
public class LocationLimitMatrServiceImpl extends BaseServiceImpl<LocationLimitMatrMapper, LocationLimitMatr> implements LocationLimitMatrService {

    @Autowired
    private LocationService locationService;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private StockService stockService;


    @Autowired
    private MatrUnitService matrUnitService;

    /**
     * 根据仓库和耗材选择入库时的默认库位
     *
     * @param warehouseId
     * @param matrId
     * @return
     */
    @Override
    public Location getSuitLocation(String warehouseId, String matrId,String packageUnit) {
        List<LocationLimitMatr> matrRefLocationList = super.list(new QueryWrapper<LocationLimitMatr>()
                .eq("matr_id", matrId)
                .eq("package_unit", packageUnit)
                .eq("warehouse_id", warehouseId));
        if (matrRefLocationList != null && matrRefLocationList.size() > 0) {
            Location location = locationService.getById(matrRefLocationList.get(0).getLocationId());
            return location;
        }
        return locationService.getDefaultLocation(warehouseId);
    }



    @Override
    public boolean saveOrUpdate(LocationLimitMatr locationLimitMatr) {
        if (StringUtils.isBlank(locationLimitMatr.getWarehouseId())
                || StringUtils.isBlank(locationLimitMatr.getMatrId())
                || StringUtils.isBlank(locationLimitMatr.getPackageUnit())
                || StringUtils.isBlank(locationLimitMatr.getLocationId())) {
            throw new BusinessException("传入数据不正确");
        }
        //判断是否存在，如已存在，无需操作

        //同一货位 耗材和单位不能重复
        LocationLimitMatr existLocationLimitMatr = super.getOne(Wrappers.<LocationLimitMatr>query()
                .eq("matr_id", locationLimitMatr.getMatrId())
                .eq("package_unit", locationLimitMatr.getPackageUnit())
                .eq("warehouse_id", locationLimitMatr.getWarehouseId())
                .ne(StringUtils.isNotBlank(locationLimitMatr.getId()),"id",locationLimitMatr.getId())
                );
        if (existLocationLimitMatr != null) {
            throw new BusinessException("您所设置的耗材以及单位已被【%s】【%s】使用，请更换其他的", existLocationLimitMatr.getWarehouseName(), existLocationLimitMatr.getLocationName());
        }
        //判断Location名称，没有则获取
        if (StringUtils.isBlank(locationLimitMatr.getLocationName())) {
            Location location = locationService.getById(locationLimitMatr.getLocationId());
            if (location == null) {
                throw new BusinessException("传入数据不正确");
            }
            locationLimitMatr.setLocationName(location.getName());
        }
        //判断Warehouse名称，没有则获取
        if (StringUtils.isBlank(locationLimitMatr.getWarehouseName())) {
            Warehouse warehouse = warehouseService.getById(locationLimitMatr.getWarehouseId());
            if (warehouse == null) {
                throw new BusinessException("传入数据不正确");
            }
            locationLimitMatr.setWarehouseName(warehouse.getName());
        }

        //判断Warehouse名称，没有则获取
        if (StringUtils.isNotBlank(locationLimitMatr.getPackageUnit()) && StringUtils.isBlank(locationLimitMatr.getUnitId())) {
            MatrUnit matrUnit = matrUnitService.getOne(Wrappers.<MatrUnit>query()
                    .eq("matr_id", locationLimitMatr.getMatrId())
                    .eq("unit", locationLimitMatr.getPackageUnit()),false);
            if (matrUnit == null) throw new BusinessException("未找到耗材单位，单位【%s】",locationLimitMatr.getPackageUnit());
            locationLimitMatr.setUnitId(matrUnit.getId());
        }

//        super.remove(new QueryWrapper<LocationLimitMatr>()
//                .eq("warehouse_id", locationLimitMatr.getWarehouseId())
//                .eq("matr_id", locationLimitMatr.getMatrId()));

        return super.saveOrUpdate(locationLimitMatr);
    }

    /**
     * @param uniqueCode
     * @param locationCode
     * @Description： 库位绑定或者解绑
     */
    @Override
    synchronized public RestResult bindOrUnbind(String uniqueCode, String locationCode) {
        RestResult restResult =RestResult.ok();
        if (StringUtils.isBlank(uniqueCode)) throw new BusinessException("缺少参数uniqueCode");
        if (StringUtils.isBlank(locationCode)) throw new BusinessException("缺少参数locationCode");
        Stock stock =stockService.getStockByUniqueCode(uniqueCode);
        if (stock == null) throw new BusinessException("未找到库存记录，唯一码【%s】",uniqueCode);
        Location location = locationService.getOne(Wrappers.<Location>query().eq("code",locationCode),false);
        if (location == null) throw new BusinessException("未找到库位，库位代码【%s】",locationCode);
        MatrUnit matrUnit = matrUnitService.getOne(Wrappers.<MatrUnit>query()
                .eq("matr_id", stock.getMatrId())
                .eq("unit", stock.getPackageUnit()),false);
        if (matrUnit == null) throw new BusinessException("未找到耗材单位，单位【%s】",stock.getPackageUnit());
        LocationLimitMatr existLocationLimitMatr = super.getOne(Wrappers.<LocationLimitMatr>query()
                .eq("matr_id", stock.getMatrId())
                .eq("unit_id",matrUnit.getId())
                .eq("warehouse_id", stock.getWarehouseId())
                ,false);
        String type= "绑定";
        if (existLocationLimitMatr != null) {
            //删除所有包装的绑定
            this.deleteByMatrId(existLocationLimitMatr.getMatrId());
//            this.removeCascadeById(existLocationLimitMatr.getId());
            type= "解绑";
        } else {
            //库位绑定耗材，绑定该耗材所有包装单位
            List<MatrUnit> matrUnits=matrUnitService.list(Wrappers.<MatrUnit>query().eq("matr_id",stock.getMatrId()));
            for(MatrUnit mUnit1:matrUnits){
                existLocationLimitMatr = new LocationLimitMatr();
            existLocationLimitMatr.setWarehouseId(stock.getWarehouseId()).setWarehouseName(stock.getWarehouseName())
                    .setLocationId(location.getId()).setLocationName(location.getName()).setLocationCode(location.getCode()).setLocationIdcode(location.getIdcode()).setLocationType(location.getType())
            .setMatrId(stock.getMatrId()).setMatrName(stock.getMatrName()).setPackageUnit(mUnit1.getUnit()).setUnitId(mUnit1.getId()).setMatrSpec(stock.getMatrSpec())
            ;
            super.save(existLocationLimitMatr);}
        }

        restResult.setMsg(String.format("库位耗材单位"+type+"成功\n库位：%s%s\n耗材：%s\n单位：%s",location.getName(),location.getCode(),  stock.getMatrName(),stock.getPackageUnit()));
        restResult.setData(existLocationLimitMatr);
        return restResult;
    }

    @Override
    public void deleteByMatrId(String matrId) {
        baseMapper.delete(new QueryWrapper<LocationLimitMatr>().eq("matr_id", matrId));
    }
}
